$(function () {
    var query = {},
        $update = $('.btn-update'),
        $delete = $('.btn-delete'),
        $create = $('.btn-create'),
        $log = $('.btn-log'),
        $plus = $('.plus'),
        strHtml = $('#form-template').html();

    var config = {
        goods: '/goods/query?size=50',//分页查询URL,
        query: '/purchaseOrderBill/queryCanSend?checkStatus=1&',//分页查询URL,
    };
    onClick($('.search'), function () {
        search({}, true)
    });
    onClick($('.export'),function () {
        generateExportUrl(search({},true,true))
    });
    $('.input-daterange .form-control:first-child').val(moment(Date.now()).format('YYYY-MM-01'));
    $('.input-daterange .form-control:last-child').val(moment(Date.now()).format('YYYY-MM-DD'));
    $.when(parent.window.getDataByUrl(config.goods, "goods"))
        .then(function (goods) {
            goods.map(function (item) {
                $('[name=goodsId]').append('<option value="' + item.id + '">' + item.name + '</option>')
            });
            $('[name=goodsId]').selectpicker({liveSearch: true,});
        });
    $('[name=goodsId]').change(function () {
        search({
            goodsId: $('[name=goodsId]').val()
        })
    });

    function search(obj, isForce,isExport) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        query_.storeName = $('[name=storeName]').val();
        query_.monthStart = $('[name=monthStart]').val();
        query_.monthEnd = $('[name=monthEnd]').val();
        query_.goodsId = $('[name=goodsId]').val();
        $loading.fadeIn();
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        var query_1 = {
            monthStart: '1970-01-01',
            monthEnd: moment(new Date($('[name=monthStart]').val()).getTime() - 1000 * 24 * 60 * 60).format('YYYY-MM-DD'),
            storeName: $('[name=storeName]').val(),
            goodsId: $('[name=goodsId]').val(),
        };
        query = query_;
        query.timestamp = Date.now();
        if(isExport){
            return config.query + ajaxArgStrGenerator(query);
        }
        $.when(
            $.get(config.query + ajaxArgStrGenerator(query)),
            $.get(config.query + ajaxArgStrGenerator(query_1))
        ).then(function (res, pre) {
            res = res[0];
            pre = pre[0];
            var pre_ = {};
            var res_1 = {};
            res.list.map(function (item) {
                res_1[item.goodsName + item.quality + item.storeName] = item;
            });
            pre.list.map(function (item) {
                if (!res_1[item.goodsName + item.quality + item.storeName]) {
                    res.list.push({
                        clienteleId: 0,
                        goodsName: item.goodsName,
                        goodsNo: item.goodsNo,
                        numberActualBuy: 0,
                        numberActualSell: 0,
                        numberInRoad: 0,
                        numberPreSell: 0,
                        numberReceive: 0,
                        numberReceiving: 0,
                        numberSending: 0,
                        page: 0,
                        paperApplier: 0,
                        quality: item.quality,
                        size: 15,
                        storeName: item.storeName,
                    });
                }
                pre_[item.goodsName + item.quality + item.storeName] = item;
            });
            pre.list.map(function (item) {
                pre_[item.goodsName + item.quality + item.storeName] = item;
            });
            res.list = _.filter(res.list, function (item) {
                var item_ = pre_[item.goodsName + item.quality + item.storeName];
                if ((!pre_[item.goodsName + item.quality + item.storeName] ||
                    toFixed((floatTool.add(item_.numberReceive * 100, floatTool.subtract(item_.numberReceiving * 100, item_.numberSending * 100))) / 100, 3) == 0) &&
                    item.numberSending == 0 &&
                    item.numberReceive == 0 && item.numberReceiving == 0)return false;
                return true;
            });
            console.log(pre_);
            var _$table = $('.table-responsive .table');
            destroyBtn();
            _$table.$table($.extend(TABLE_SETTING, {
                checkbox: false, // 是否显示复选框
                seqNum: true, // 是否显示序号
                sort: search, //排序回调函数
                destroyBtn: destroyBtn, //禁用按钮
                createBtn: createBtn, // 启用她扭
                toolbar: '.toolbar',
                enableSetting: true,//允许自定义显示列
                search: function (obj) { //搜索框查询函数
                    search(obj)
                },
                fields: [
                    {
                        name: 'goodsName',
                        _sort: 'goods_name', label: '产品名称',
                    },
                    {
                        name: 'goodsNo', _sort: 'goods_no', label: '产品编码',
                    },
                    {
                        name: 'pre', label: '上期结转',
                        total: true, filter: function (item) {
                        if (pre_[item.goodsName + item.quality + item.storeName]) {
                            item = pre_[item.goodsName + item.quality + item.storeName];
                            return toFixed((floatTool.add(item.numberReceive * 100, floatTool.subtract(item.numberReceiving * 100, item.numberSending * 100))) / 100, 3)
                        } else {
                            return 0;
                        }
                    }
                    },
                    {name: 'storeName', _sort: 'store_name', label: '库区'},
                    {name: 'quality', _sort: 'quality', label: '品质规格'},
                    {
                        name: 'numberSending', total: true, label: '发货中数量',
                        enableSort: true, filter: function (item) {
                        return item.numberSending;
                    }
                    },
                    {
                        name: 'numberReceive',
                        total: true,
                        label: '实际库存数量',
                        enableSort: true,
                        filter: function (item) {
                            return item.numberReceive;
                        }
                    },
                    {
                        name: 'numberReceiving', total: true, label: '收货中数量', filter: function (item) {
                        return item.numberReceiving;
                    }
                    },
                    {
                        name: 'canSendNumber',
                        label: '可发货数量', total: true,
                        filter: function (item) {
                            var pre__ = 0;
                            var item_ =pre_[item.goodsName + item.quality + item.storeName];
                            if (item_) {
                                pre__ = toFixed((floatTool.add(item_.numberReceive * 100, floatTool.subtract(item_.numberReceiving * 100, item_.numberSending * 100))) / 100, 3)
                            }
                            console.log("pre__:"+pre__)
                            return floatTool.add(pre__, toFixed((floatTool.add(item.numberReceive * 100, floatTool.subtract(item.numberReceiving * 100, item.numberSending * 100))) / 100, 3));
                        }
                    },
                ],
                data: res.list || [],
            }));
            var page = res.page;
            pageInit(page, query, search);
        });
    }

    search({}, true);
});